package com.ssm.controller;

import com.alibaba.fastjson.JSONArray;
import com.ssm.pojo.Role;
import com.ssm.pojo.User;
import com.ssm.service.role.RoleService;
import com.ssm.service.user.UserService;
import com.ssm.util.PageSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/user")
public class UserController {
    private static Integer counter=0;
    @Autowired
    @Qualifier("userServiceImpl")
    private UserService userService;
    @Autowired
    @Qualifier("roleServiceImpl")
    private RoleService roleService;
    @RequestMapping("/login")
    public String getlogin(User user,HttpServletRequest request, Model model){
        String userCode = request.getParameter("userCode");
        String userPassword = request.getParameter("userPassword");
        String targetView = "";
        user.setUserCode(userCode);
        user.setUserPassword(userPassword);
        User loginUser = userService.login(user);
        if (loginUser!=null){
            request.getSession().setAttribute("loginUser", loginUser);
            targetView = "frame";
        }else{
            targetView = "error";
        }
        return targetView;
    }
    @RequestMapping("/logout")
    public void logOut(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        if(request.getSession().getAttribute("loginUser")!=null){
            request.getSession().removeAttribute("loginUser");
        }
        response.sendRedirect("login.jsp");
    }
    @RequestMapping("/list")
    public String userList(String userName,Integer userRole, Integer pageIndex,HttpServletRequest request, Model model) throws Exception {
        PageSupport ps = new PageSupport();
        int totalCount = userService.getUserCount(userName, userRole);
        ps.setPageSize(5);/*设置页面大小为5*/
        ps.setTotalCount(totalCount);/*设置用户数量*/
        List<Role> roleList = roleService.getRoleList();
        model.addAttribute("roleList",roleList);
        if (pageIndex!=null){
            ps.setCurrentPageNo(pageIndex);
        }
        int offset = ps.getOffset();/*获取当前页*/
        int totalPageCount = ps.getTotalPageCount();
        List<User> userList = userService.getUserList(userName, userRole, offset, ps.getPageSize());
        model.addAttribute("userName",userName);
        model.addAttribute("queryUserRole",userRole);
        model.addAttribute("totalCount",totalCount);
        model.addAttribute("currentPageNo",ps.getCurrentPageNo());
        model.addAttribute("totalPageCount",totalPageCount);
        model.addAttribute("userList",userList);
        model.addAttribute("roleList",roleList);
        return "userlist";
    }
    @RequestMapping("/toAddUser")
    public String toAddUser(Model model){
        List<Role> roleList = roleService.getRoleList();
        model.addAttribute("roleList",roleList);
        return "useradd";
    }
    @RequestMapping("/addUser")
    public void addUser(User user,HttpServletResponse response) throws ServletException, IOException {
        int rowCount = userService.addUser(user);
        if (rowCount>0){
            System.out.println("添加用户成功!");
        }else {
            System.out.println("添加用户失败!");
        }
        response.sendRedirect("/user/list");
    }
    @RequestMapping("/registerUser")
    public void register(User user,HttpServletResponse response) throws ServletException, IOException {
        int rowCount = userService.addUser(user);
        if (rowCount>0){
            System.out.println("注册用户成功!");
        }else {
            System.out.println("注册用户失败!");
        }
        response.sendRedirect("login.jsp");
    }
    @RequestMapping("/isExist")
    @ResponseBody
    public String isUserExist(String userCode){
        Map map = new HashMap();
        if (userCode.replaceAll(" ", "").equals("")||(userCode==null)){
            map.put("result", "exist");
        }else{
            User userByUserCode = userService.getUserByUserCode(userCode);
            if (userByUserCode!=null) {
                map.put("result", "exist");
            }else{
                map.put("result", "not exist");
            }
        }
        return JSONArray.toJSONString(map);
    }
    @RequestMapping("/toUserView")
    public String toUserView(@RequestParam("userid") Integer id, Model model){
        User userById = userService.getUserById(id);
        System.out.println(userById);
        model.addAttribute("user",userById);
        return "userview";
    }
    @RequestMapping("/deleteUser")
    @ResponseBody
    public String deleteUser(@RequestParam("userid") Integer id) throws ServletException, IOException, SQLException {
        User userById = userService.getUserById(id);
        Map map = new HashMap();
        if (userById==null){
            map.put("result", "not exist");
        }else{
            int rowCount = userService.deleteUserById(id);
            if (rowCount>0){
                map.put("result", "true");
                System.out.println("删除用户成功!");
            }else{
                map.put("result", "false");
                System.out.println("删除用户失败!");
            }
        }
        String data = JSONArray.toJSONString(map);
        return data;
    }
    @RequestMapping("/toModifyUser")
    public String toModifyUser(@RequestParam("userid") Integer id,Model model){
        User userById = userService.getUserById(id);
        List<Role> roleList = roleService.getRoleList();
        String s = JSONArray.toJSONString(roleList);
        System.out.println(s);
        model.addAttribute("user",userById);
        model.addAttribute("roleList",roleList);
        return "usermodify";
    }
    @RequestMapping("/modifyUser")
    public void modifyUser(@RequestParam("userId") Integer id,User user, HttpServletResponse response) throws SQLException, IOException {
        user.setId(id);
        System.out.println(user);
        int rowCount = userService.modifyUser(user);
        if (rowCount>0){
            System.out.println("修改成功!");
        }else{
            System.out.println("修改失败");
        }
        response.sendRedirect("/user/list");
    }
    @RequestMapping("/toPwdModify")
    public String toPwdModify(Model model, HttpSession session){
        User loginUser = (User) session.getAttribute("loginUser");
        model.addAttribute("userId",loginUser.getId());
        return "pwdmodify";
    }
    @RequestMapping("/pwdModify")
    public void pwdModify(@RequestParam("userId") Integer id,@RequestParam("newpassword") String newPassword,HttpServletResponse response) throws SQLException, IOException {
        int rowCount = userService.updatePwd(id, newPassword);
        if (rowCount>0){
            System.out.println("密码修改成功!");
        }else{
            System.out.println("密码修改失败!");
        }
        response.sendRedirect("/user/logout");
    }
    @RequestMapping("/verifyPwd")
    @ResponseBody
    public String verifyPwd(@RequestParam("userId") Integer id,String oldpassword){
        User userById = userService.getUserById(id);
        Map map = new HashMap<>();
        if (oldpassword.replaceAll(" ", "").equals("")){
            map.put("result", "error");
        }else if (userById.getUserPassword().equals(oldpassword)){
            map.put("result", "true");
        }else{
            map.put("result", "false");
        }
        String data = JSONArray.toJSONString(map);
        return data;
    }
}
